/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controleur;

import newpackage.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author SOGOBA
 */
public class HealthSampleServlet extends HttpServlet {

    public static final long serialVersionUID = 1;
    // the name of the session variable that holds our AuthSub token
    public static final String HEALTH_TOKEN = "healthToken";

    /**
     * Returns URI of the current page
     *
     * @param request the request
     * @return the URI the user is currently requesting.
     * @throws MalformedURLException When the Java URL constructor gets angry.
     */
    private String getCurrentUrl(HttpServletRequest request)
            throws MalformedURLException {
        URL currentUrl = new URL(request.getScheme(), request.getServerName(),
                request.getServerPort(), request.getRequestURI());
        return currentUrl.toString();
    }

    /**
     * Save AuthSubToken into session.
     *
     * @param request The request
     * @param response The response
     * @throws IOException
     */
    private void processAcceptAuthSubToken(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        /*
         * Request is caused by a user being redirected back from AuthSub login
         */
        if (request.getParameter("token") != null) {
            HealthSample sp = new HealthSample();
            try {
                String token = sp.exchangeAuthSubToken(request.getParameter("token"));
                request.getSession().setAttribute(HEALTH_TOKEN, token);
                response.sendRedirect("HealthSampleServlet?action=outputProfile");
            } catch (HealthSampleException e) {
                System.err.println("Authentication exception: " + e.getMessage());
            }
        }
    }

    /**
     * Logs the user out by clearing the session.
     *
     * @param request The request
     * @param response The response
     * @throws IOException
     */
    private void processLogout(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
        request.getSession().removeAttribute(HEALTH_TOKEN);
        response.sendRedirect("HealthSampleServlet?action=outputIntroPage");
    }

    /**
     * Default action - output intro page.
     *
     * @param request The request
     * @param response The response
     * @throws ServletException
     * @throws IOException
     */
    private void processOutputIntroPage(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String authUrl = HealthSample.getAuthSubUrl(getCurrentUrl(request)
                + "HealthSampleServlet?action=handleToken");
        request.setAttribute("authUrl", authUrl);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(
                "/WEB-INF/jsp/outputIntroPage.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * Output profile visible from the given token.
     *
     * @param request The request
     * @param response The response
     * @throws ServletException
     * @throws IOException
     */
    private void processOutputProfile(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        HealthSample sp = new HealthSample();
        try {
            String token = (String) request.getSession().getAttribute(HEALTH_TOKEN);
            if (token == null) {
                response.sendRedirect("HealthSampleServlet?action=outputIntroPage");
                return;
            }
            sp.setAuthSubToken(token);
            request.setAttribute("profile", sp.getProfile());
        } catch (HealthSampleException e) {
            System.err.println("Profile retrieval exception: " + e.getMessage());
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(
                "/WEB-INF/jsp/outputProfile.jsp");
        dispatcher.forward(request, response);
    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * Determine action attempted
             */
            String action = (request.getParameter("action")) == null
                    ? "outputIntroPage" : request.getParameter("action");

            if ("outputIntroPage".equals(action)) {
                processOutputIntroPage(request, response);
            } else if ("handleToken".equals(action)) {
                processAcceptAuthSubToken(request, response);
            } else if ("outputProfile".equals(action)) {
                processOutputProfile(request, response);
            } else if ("logout".equals(action)) {
                processLogout(request, response);
            } else {
                throw new ServletException("Error! Bad Action!'" + action + "'");
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
